﻿using JIG_SoftTemplate.ViewModels;
using System.Reflection;
using System.Windows.Controls;

namespace JIG_SoftTemplate.Common.Services
{
    public class NavigationService
    {
        private Frame? mainFrame;

        public void SetMainFrame(Frame frame) => mainFrame = frame;

        private Type? FindView<VM>()
        {
            return Assembly
                .GetAssembly(typeof(VM))
                ?.GetTypes()
                .FirstOrDefault(t => t.Name == typeof(VM).Name.Replace("ViewModel", ""));
        }

        public void Navigate<VM>()
            where VM : ViewModelBase
        {
            Navigate<VM>(null);
        }

        public void Navigate<VM>(Dictionary<string, object?>? extraData)
            where VM : ViewModelBase
        {
            var viewType = FindView<VM>();
            if (viewType is null)
                return;

            var page = App.Current.Services.GetService(viewType) as Page;
            mainFrame?.Navigate(page, extraData);
        }
    }
}
